package com.inspur.icity.bus.base.core.service;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ListObjectsRequest;
import com.aliyun.openservices.oss.model.OSSObject;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;


public class OssService {
    public static String BUCKETNAME = "westeros-dragonstone";

    OSSClient client;
    public OssService() {
        client = newOSSClient();
        if(!client.doesBucketExist(BUCKETNAME)){
            client.createBucket(BUCKETNAME);
        }
    }
    public OSSClient getOSSClient(){
        return client;
    }

    public PutObjectResult putObject(String key, InputStream input, ObjectMetadata metadata){
        return client.putObject(BUCKETNAME, key ,input, metadata);
    }

    public OSSObject getObject(String key){
        return client.getObject(BUCKETNAME, key);
    }

    public void deleteObject(String key){
        try{
            client.deleteObject(BUCKETNAME, key);
        }catch (Exception e){
            client = newOSSClient();
            client.deleteObject(BUCKETNAME, key);
        }
    }

    public ListObjectsRequest newListObjectsRequest(){
        return new ListObjectsRequest(BUCKETNAME);
    }

    public byte[] getObjectBytes(String key) throws IOException {
        OSSObject object = this.getObject(key);
        InputStream is = object.getObjectContent();
        return IOUtils.toByteArray(is);
    }

    private OSSClient newOSSClient(){
        return new OSSClient("http://oss-cn-qingdao.aliyuncs.com","xBrGXyxZez1TUNKl", "G5RIYAnVjLhXwiHEmT9PayLXkkOPtq");
    }

}
